/**
 * Created by lixiaodi on 2019/06/10.
 */
mini.parse();
var grid = mini.get('datagrid1');
var searchForm = new mini.Form("searchFormBar");	//搜索栏目
var sendPeopleNameEl = mini.get('sendPeopleName');	//发件人元素

var stateSql = '';										//查询信息列表(带状态)sql
//页面初始化
$(function (){
	//列表显示
	httpRequest('0','');
});
//选择发件人
function changePerson(){
	mini.open({
        url: bootPATH + "../frame/frame1/pages/booking/Mail/changePerson.html",
        title: "选择发件人",
        width: 600,
        height: 400,
        ondestroy: function (action) {
            //if (action == "close") return false;
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.GetData();
                data = mini.clone(data);    //必须
                //赋值
                sendPeopleNameEl.setValue(data.operatorId);
                sendPeopleNameEl.setText(data.perName);
            }
        }
    });
}
//表格的操作按钮绘制
function onActionRenderer(e) {
    var grid = e.sender;
    var record = e.record;
    var uid = record._uid;
    var rowIndex = e.rowIndex;
    var s = ' <a class="mini-button Edit_Button" href="javascript:onsendOut(\'' + uid + '\')" >发送</a>'
    		+ ' <a class="mini-button Edit_Button" href="javascript:onForward(\'' + uid + '\')" >转发</a>'
    		+ ' <a class="mini-button Edit_Button" href="javascript:onRemove(\'' + uid + '\')" >删除</a>';
    return s;
}
//根据条件查询
function onSearch(){
	//得到查询条件数据
	searchData = searchForm.getData();
	//拼接查询sql
	var dataStr = stateSql;       //存放sql
	//通过name得到日期区间得元素并且得到用户填写得值
    var colum1 = mini.getByName('push_time').getValue();
    var colum2 = mini.getByName('push_time2').getValue();
    //如果值都不为空，那么执行sql语句
    if(colum1 != "" && colum2 != ""){
        if(tab(colum1,colum2)){
            colum1 = mini.formatDate(colum1,"yyyy-MM-dd");       //时间格式
            colum2 = mini.formatDate(colum2,"yyyy-MM-dd");       //时间格式
            dataStr += " and " + 'push_time' + " between '" + colum1 + "' and " + "'" + colum2 + "'";
        }else{
            mini.alert("第二个日期不能大于以一个日期");
        }
    }else if(colum1 == "" && colum2 != ""){
        colum2 = mini.formatDate(colum2,"yyyy-MM-dd");       //时间格式
        dataStr += " and push_time" + " <= " + "'" + colum2 + "'";
    }else if(colum1 != "" && colum2 == ""){
        colum1 = mini.formatDate(colum1,"yyyy-MM-dd");       //时间格式
        dataStr += " and push_time" + " >= " + "'" + colum1 + "'";
    }
    //删除时间字段
    delete searchData.push_time;
    delete searchData.push_time2;
    //除时间以外的sql拼接
    for(var key in searchData){
    	if(searchData[key]){
    		if(key == 'book_isbn'){
    			dataStr += " and "  + key + " in (" + searchData[key] + ")";
    		}else if(key == 'send_peopleName'){
    			dataStr += " and send_people like '%" + searchData[key] + "%'";
    		}else{
    			dataStr += " and "  + key + " like '%" + searchData[key] + "%'";
    		}
    	}
    }
    var searchSql = dataStr;
	//查询数据
	httpRequest('0',searchSql);
}
//发送
function onsendOut(row_uid){
	//根据uid获取行数据
	var row = grid.getRowByUID(row_uid);
	if(row){
		row.types = '草稿发送';
		//将需要编辑的数据带过去
		localStorage.setItem("mailData",JSON.stringify(row));
		onJump('发送邮件');
	}else{
		mini.alert('请选择需要发送的邮件');
	}
}
//转发
function onForward(row_uid){
	console.log('转发');
	//根据uid获取行数据
	var row = grid.getRowByUID(row_uid);
	row.types = '转发';
	if(row){
		//将需要编辑的数据带过去
		localStorage.setItem("mailData",JSON.stringify(row));
		onJump('转发邮件');
	}
}
//删除（删除单个，行内按钮）
function onRemove(row_uid){
	//根据uid获取行数据
	var row = grid.getRowByUID(row_uid);
	if(row){
		var sendId = row.msg_info_id;
		grid.loading("操作中，请稍后......");
		$.ajax({
			url: ajaxUrl + "/msg/delReadyMsgs.do?ids=" + sendId,
            type: "post",
            success: function (data) {
            	grid.unmask();
                if(data.status == 200){
                	showTips(data.data);
                	httpRequest();
                }else{
                	mini.alert(data.data);
                }
            },
            error: function () {
                mini.alert('失败');
            }
        });
	}
}
//删除多个（按钮栏中的删除）
function onRemoves() {
    var rows = grid.getSelecteds();
    if (rows.length > 0) {
        mini.confirm("确定删除选中记录？","系统提示",function(action){
            if (action == "ok") {
                var ids = [];
                for (var i = 0, l = rows.length; i < l; i++) {
                    var r = rows[i];
                    ids.push(r.msg_info_id);
                }
                var id = ids.join(',');
                grid.loading("操作中，请稍后......");
                $.ajax({
                    url: ajaxUrl + "/msg/delReadyMsgs.do?ids=" + id,
                    type: "post",
                    success: function (data) {
                    	grid.unmask();
                    	if(data.status == 200){
                        	showTips(data.data);
                        	httpRequest();
                        }else{
                        	showTips(data.data);
                        }
                    },
                    error: function () {
                        mini.alert('失败');
                    }
                });
            }
        })
    }else {
        mini.alert("请选中一条记录");
    }
}
//彻底删除
function onDestroy(){
	 var rows = grid.getSelecteds();
	 if (rows.length > 0) {
		 mini.confirm("确定彻底删除选中记录？","系统提示",function(action){
			 if(action == "ok"){
				 var ids = [];
	             for (var i = 0, l = rows.length; i < l; i++) {
	            	 var r = rows[i];
	            	 ids.push(r.msg_info_id);
	             }
	             var id = ids.join(',');
	             grid.loading("操作中，请稍后......");
	             $.ajax({
	                    url: ajaxUrl + "/msg/delReadyMsgs.do?ids=" + id,
	                    type:"post",
	                    success: function (data) {
	                    	grid.unmask();
	                        if(data.status == 200){
	                        	showTips(data.data);
	                        	httpRequest();
	                        }else{
	                        	mini.alert(data.data);
	                        }
	                    },
	                    error: function () {
	                        mini.alert('失败');
	                    }
	                });  
			 }
		 });
	 } else {
		 mini.alert("请选中一条记录");
	 }
}
//列表显示
function httpRequest(pageIndex,paramSql){
    var pager=grid.getBottomPager();
	var pageObj = {
			pageSize: '500',
			pageNum: pageIndex,
			paramSql: paramSql
	}
	var pageStr = JSON.stringify(pageObj);
	grid.loading('请稍后...');
	$.ajax({
		url: ajaxUrl + '/msg/readyMsgList.do',
        type: "post",
        data: pageStr,
		contentType : "application/json",
        success: function (data) {
        	grid.unmask();
        	if(data.status == 706){
        		showTips(data.data)
        	}else if(data.status == 200){
        		var list = data.data;
        		list.forEach((item)=>{
        			item.userNames = item.userNames.substring(0,item.userNames.length-1);
        			if(item.push_time){
        				item.push_time = formatDateSec(item.push_time);
        			}else{
        				item.push_time = '';
        			}
        		});
        		grid.setData(list);
        		pager.set({"totalCount":data.count.count});        //设置分页总数
				gridData = list;
        	}else{
        		mini.alert(data.data);
        	}
        	
        },
        error: function () {
            mini.alert('失败');
        }
	})
}
//跳转函数
function onJump(text){
	//跳转
	var item = {
		//id: text,
	    iconCls: "fa fa-desktop",
	    text: text,
	    url: "../pages/booking/Mail/mAddAndEdit.html"
	};
	parent.activeTab(item);//与父页面通信
}
//提示信息
function showTips(text) {
    mini.showTips({
        content: "<b>" + text + "</b>",
        state: "success",
        x: "center",
        y: "center",
        timeout: 2000
    });
}